package com.lxr0860.lxr0860production_test.utils;

import android.annotation.SuppressLint;

public class MyUtils {
    //16进制数累加，取低位，溢出舍弃
    public static String Add(String data) {
        if (data == null || data.equals("")) {
            return "";
        }
        data = data.replace(" ","");
//        System.out.println(data);
        int total = 0;
        int len = data.length();
        int num = 0;
        while (num < len) {
            String s = data.substring(num, num + 2);
//            System.out.println(s);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }
/**
 * 用256求余最大是255，即16进制的FF
 */
        int mod = total % 256;
        String hex = Integer.toHexString(mod);
        len = hex.length();
// 如果不够校验位的长度，补0,这里用的是两位校验
        if (len < 2) {
            hex = "0" + hex;
        }
        return hex;
    }


    @SuppressLint("DefaultLocale")
    public static byte[] hexStringToBytes(String string) {
        String hexString = string.replaceAll(" ", "").toUpperCase();

        if (hexString.length() <= 0)
            return null;

        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));

        }
        return d;
    }
    public static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
    public static String hex2DebugHexString(byte[] b) {
        int len = b.length;
        int[] x = new int[len];
        String[] y = new String[len];
        StringBuilder str = new StringBuilder();
        int j = 0;
        for (; j < len; j++) {
            x[j] = b[j] & 0xff;
            y[j] = Integer.toHexString(x[j]);
            while (y[j].length() < 2) {
                y[j] = "0" + y[j];
            }
            str.append(y[j]);
            str.append(" ");
        }
        return new String(str).toUpperCase();
    }
    public static String hex2DebugHexString(byte b) {

        int[] x = new int[2];
        String[] y = new String[2];
        StringBuilder str = new StringBuilder();


            x[0] = b & 0xff;
            y[0] = Integer.toHexString(x[0]);
            while (y[0].length() < 2) {
                y[0] = "0" + y[0];
            }
            str.append(y[0]);


        return new String(str).toUpperCase();
    }

}
